package view;

import HibernateConfig.HibernateUtil;
import controller.WorkerTracking;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Paquete;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.MaxLengthTextDocument;

public class BusquedaPaquete extends javax.swing.JFrame {

    Vector columnasTablaPaquetes; // vector con los nombres de las columnas de la tabla de paquetes
    DefaultTableModel modeloTablaPaquetes;    //modelo para la tabla de envios
    List<Paquete> listaFilasTablaPaquetes;
    Integer numfilas;

    public List<Paquete> getListaFilasTablaPaquetes() {
        return listaFilasTablaPaquetes;
    }

    public void setListaFilasTablaPaquetes(List<Paquete> listaFilasTablaPaquetes) {
        this.listaFilasTablaPaquetes = listaFilasTablaPaquetes;
    }

    public BusquedaPaquete() {
        initComponents();
        iniciaCampos(1);
        numfilas = 0;
       // this.rdPersona.doClick();

        //Inicializo la tabla
        listaFilasTablaPaquetes = new ArrayList<Paquete>(); //lista de clientes para la tabla
        columnasTablaPaquetes = new Vector(); //Cabecera
        columnasTablaPaquetes.add("Id Paquete");
        columnasTablaPaquetes.add("Cliente");
        columnasTablaPaquetes.add("Origen");
        columnasTablaPaquetes.add("Destino");
        columnasTablaPaquetes.add("Estado");
        modeloTablaPaquetes = new DefaultTableModel(this.columnasTablaPaquetes, 0) {
            public boolean isCellEditable(int row, int column) { // para que no se pueda editar directamente la tabla
                return false;
            }
        };

        this.tblPaquete.setModel(modeloTablaPaquetes);
        this.tblPaquete.setCellSelectionEnabled(false); // para que no se puedan seleccionar celdas individuales
        this.tblPaquete.setRowSelectionAllowed(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        txtNombre = new javax.swing.JTextField();
        nombre = new javax.swing.JLabel();
        dni = new javax.swing.JLabel();
        txtDocId = new javax.swing.JTextField();
        rdPersona = new javax.swing.JRadioButton();
        rdEmpresa = new javax.swing.JRadioButton();
        apellido = new javax.swing.JLabel();
        txtApPat = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtIDPaq = new javax.swing.JTextField();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPaquete = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Buscar Paquetes");
        setResizable(false);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios de Búsqueda"));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cliente"));

        txtNombre.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtNombre.setText("Pablo");
        txtNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNombreActionPerformed(evt);
            }
        });
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        nombre.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        nombre.setText("Nombre");

        dni.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        dni.setText("Doc. Identidad");

        txtDocId.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtDocId.setText("85674321");
        txtDocId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDocIdKeyTyped(evt);
            }
        });

        rdPersona.setText("Persona Natural");
        rdPersona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdPersonaActionPerformed(evt);
            }
        });

        rdEmpresa.setText("Empresa");
        rdEmpresa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdEmpresaActionPerformed(evt);
            }
        });

        apellido.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        apellido.setText("Apellido Paterno:");

        txtApPat.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtApPat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApPatKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(rdPersona)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(rdEmpresa)
                        .addGap(17, 17, 17))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(dni, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(11, 11, 11)
                                .addComponent(nombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtApPat, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDocId, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(29, 29, 29))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rdPersona)
                    .addComponent(rdEmpresa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombre)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtApPat, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dni, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDocId, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnBuscar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/buscar.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnLimpiar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Limpiar.png"))); // NOI18N
        btnLimpiar.setText("Limpiar");
        btnLimpiar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLimpiarMouseClicked(evt);
            }
        });
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Paquete"));

        jLabel3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel3.setText("Id Paquete");

        txtIDPaq.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtIDPaq.setText("001");
        txtIDPaq.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtIDPaqKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtIDPaq, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtIDPaq, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar)
                    .addComponent(btnLimpiar)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(btnBuscar)
                .addGap(18, 18, 18)
                .addComponent(btnLimpiar))
        );

        btnAceptar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/aceptar.png"))); // NOI18N
        btnAceptar.setText("Iniciar Simulación");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        tblPaquete.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Id Paquete", "Cliente", "Origen", "Destino", "Estado"
            }
        ));
        jScrollPane1.setViewportView(tblPaquete);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 690, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(204, 204, 204)
                .addComponent(btnAceptar)
                .addGap(38, 38, 38)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar)))
        );

        setSize(new java.awt.Dimension(754, 511));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnLimpiarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLimpiarMouseClicked
        // TODO add your handling code here:
        this.limpiarTxt();
    }//GEN-LAST:event_btnLimpiarMouseClicked

    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        this.dispose();
        new Menu().setVisible(true);
    }//GEN-LAST:event_btnCancelarMouseClicked

    private void rdPersonaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdPersonaActionPerformed

        iniciaCampos(1);
        this.txtApPat.setVisible(true);
        this.apellido.setVisible(true);
        this.dni.setText("Doc. Identidad:");
        this.nombre.setText("Nombre:");
        this.limpiarTxt();
        this.rdEmpresa.setSelected(false);
        if(!rdPersona.isSelected()&&!rdEmpresa.isSelected()){
            this.txtApPat.setEnabled(false);
            this.txtDocId.setEnabled(false);
            this.txtNombre.setEnabled(false);
            this.txtIDPaq.setEnabled(true);
        }else{
            this.txtApPat.setEnabled(true);
            this.txtDocId.setEnabled(true);
            this.txtNombre.setEnabled(true);
            this.txtIDPaq.setEnabled(false);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_rdPersonaActionPerformed

    private void rdEmpresaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdEmpresaActionPerformed

        iniciaCampos(2);
        this.txtApPat.setVisible(false);
        this.apellido.setVisible(false);
        this.dni.setText("RUC:");
        this.nombre.setText("Razón Social:");
        this.limpiarTxt();
        this.rdPersona.setSelected(false);
        if(!(rdPersona.isSelected())&&!(rdEmpresa.isSelected())){
            this.txtNombre.setEnabled(false);
            this.txtDocId.setEnabled(false);
            this.txtIDPaq.setEnabled(true);
        }else{
            this.txtNombre.setEnabled(true);
            this.txtDocId.setEnabled(true);
            this.txtIDPaq.setEnabled(false);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_rdEmpresaActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        this.limpiarTxt();
        // TODO add your handling code here:
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed

        Paquete paqueteTemp;
        Session sesion = HibernateUtil.getSessionFactory().openSession();
        Transaction transaccion = null;
        try {
            transaccion = sesion.beginTransaction();
            String hql = "FROM Paquete p ";
            int nFiltros = 0;

            for (int i = numfilas - 1; i >= 0; i--) {
                modeloTablaPaquetes.removeRow(i);
            }
            numfilas = 0;
            listaFilasTablaPaquetes.clear();

            if (txtIDPaq.getText().length() > 0) {
                if (nFiltros == 0) {
                    hql = hql.concat("WHERE ");
                }
                hql = hql.concat("p.idPaquete='").concat(txtIDPaq.getText()).concat("'");
                nFiltros++;
            }

            if (rdPersona.isSelected()) {//Buscar por persona natural
                if (txtNombre.getText().length() > 0) {
                    if (nFiltros == 0) {
                        hql = hql.concat("WHERE ");
                    }
                    if (nFiltros > 0) {
                        hql = hql.concat(" and ");
                    }
                    hql = hql.concat("p.cliente.nombres like '%").concat(txtNombre.getText()).concat("%'");
                    nFiltros++;
                }
                if (txtApPat.getText().length() > 0) {
                    System.out.println(nFiltros);
                    if (nFiltros == 0) {
                        hql = hql.concat("WHERE ");
                    }
                    if (nFiltros > 0) {
                        hql = hql.concat(" and ");
                    }
                    hql = hql.concat("p.cliente.apPaterno like '%").concat(txtApPat.getText()).concat("%'");
                    nFiltros++;
                }
                if (txtDocId.getText().length() > 0) {
                    if (nFiltros > 0) {
                        hql = hql.concat(" and ");
                    }
                    hql = hql.concat("p.cliente.dni='").concat(txtDocId.getText()).concat("'");
                    nFiltros++;
                }
            } else if(rdEmpresa.isSelected()) {//Buscar por empresa
                if (txtNombre.getText().length() > 0) {
                    if (nFiltros == 0) {
                        hql = hql.concat("WHERE ");
                    }
                    if (nFiltros > 0) {
                        hql = hql.concat(" and ");
                    }
                    hql = hql.concat("p.cliente.razonSocial like '%").concat(txtNombre.getText()).concat("%'");
                    nFiltros++;
                }
                if (txtDocId.getText().length() > 0) {
                    if (nFiltros == 0) {
                        hql = hql.concat("WHERE ");
                    }
                    if (nFiltros > 0) {
                        hql = hql.concat(" and ");
                    }
                    hql = hql.concat("p.cliente.ruc='").concat(txtDocId.getText()).concat("'");
                    nFiltros++;
                }
            }

            List paquetes = sesion.createQuery(hql).list();   // query para obtener los paquetes
            Iterator iterador = paquetes.iterator();

            while (iterador.hasNext()) {   //mientras hayan paquetes en el iterador
                //creo objeto paquete
                paqueteTemp = (Paquete) iterador.next();   // obtengo un paquete de la lista 
                listaFilasTablaPaquetes.add(paqueteTemp);   //agrego nodo a la lista de nodos
            }
            List<Paquete> listaux=new ArrayList<Paquete>();
            for (int i = 0; i < listaFilasTablaPaquetes.size(); i++) {

                if (rdPersona.isSelected() && (listaFilasTablaPaquetes.get(i).getCliente().getNombres() != null)) {
                    Object[] o = new Object[5];
                    Paquete paqueaux=listaFilasTablaPaquetes.get(i);
                    numfilas++;
                    o[0] = listaFilasTablaPaquetes.get(i).getIdPaquete();
                    o[1] = listaFilasTablaPaquetes.get(i).getCliente().getNombres().concat(" " + listaFilasTablaPaquetes.get(i).getCliente().getApPaterno()).concat(" " + listaFilasTablaPaquetes.get(i).getCliente().getApMaterno());
                    o[2] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadOrigen().getCiudad();
                    o[3] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadDestino().getCiudad();
                    o[4] = listaFilasTablaPaquetes.get(i).getEstado();
                    modeloTablaPaquetes.addRow(o);
                    listaux.add(paqueaux);
                } else if (rdEmpresa.isSelected() && (listaFilasTablaPaquetes.get(i).getCliente().getRazonSocial() != null)) {
                    Object[] o = new Object[5];
                    Paquete paqueaux=listaFilasTablaPaquetes.get(i);
                    numfilas++;
                    o[0] = listaFilasTablaPaquetes.get(i).getIdPaquete();
                    o[1] = listaFilasTablaPaquetes.get(i).getCliente().getRazonSocial();
                    o[2] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadOrigen().getCiudad();
                    o[3] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadDestino().getCiudad();
                    o[4] = listaFilasTablaPaquetes.get(i).getEstado();
                    modeloTablaPaquetes.addRow(o);
                    listaux.add(paqueaux);
                }else if(!rdEmpresa.isSelected()&& !rdPersona.isSelected()){
                    Object[] o = new Object[5];
                    Paquete paqueaux=listaFilasTablaPaquetes.get(i);
                    numfilas++;
                    o[0] = listaFilasTablaPaquetes.get(i).getIdPaquete();
                    if(listaFilasTablaPaquetes.get(i).getCliente().getTipo().equals("natural")){
                       o[1] = listaFilasTablaPaquetes.get(i).getCliente().getNombres().concat(" " + listaFilasTablaPaquetes.get(i).getCliente().getApPaterno()).concat(" " + listaFilasTablaPaquetes.get(i).getCliente().getApMaterno());
                    }else{
                       o[1] = listaFilasTablaPaquetes.get(i).getCliente().getRazonSocial();
                    }
                    o[2] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadOrigen().getCiudad();
                    o[3] = listaFilasTablaPaquetes.get(i).getCiudadByIdCiudadDestino().getCiudad();
                    o[4] = listaFilasTablaPaquetes.get(i).getEstado();
                    modeloTablaPaquetes.addRow(o);
                    listaux.add(paqueaux);
                }
            }
            listaFilasTablaPaquetes=listaux;
        } catch (HibernateException ex) {
            transaccion.rollback();
            System.err.println("Got an exception! ");
            System.err.println(ex.getMessage());
        } finally {
            sesion.close(); // cierro la sesion (BD)
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void txtIDPaqKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIDPaqKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
        this.txtNombre.setText("");
        this.txtDocId.setText("");
        this.txtApPat.setText("");
        if (listaFilasTablaPaquetes != null) {
            for (int i = numfilas - 1; i >= 0; i--) {
                modeloTablaPaquetes.removeRow(i);
            }
            listaFilasTablaPaquetes.clear();
        }
        numfilas = 0;
        this.rdPersona.setSelected(false);
        this.rdEmpresa.setSelected(false);
        this.txtNombre.setEnabled(false);
        this.txtDocId.setEnabled(false);
        this.txtApPat.setEnabled(false);
    }//GEN-LAST:event_txtIDPaqKeyTyped

    private void txtDocIdKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDocIdKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDocIdKeyTyped

    private void txtApPatKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApPatKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtApPatKeyTyped

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped

        char vChar = evt.getKeyChar();
        if(rdPersona.isSelected()){
            if (!(Character.isAlphabetic(vChar)
                    || (Character.isSpaceChar(vChar))
                    || (vChar == KeyEvent.VK_BACK_SPACE)
                    || (vChar == KeyEvent.VK_DELETE) )) {
                evt.consume();
            }
        }else if(rdEmpresa.isSelected()){
            if (!(Character.isAlphabetic(vChar)
                    || (Character.isSpaceChar(vChar))
                    || (vChar == KeyEvent.VK_BACK_SPACE)
                    || (vChar == KeyEvent.VK_DELETE)
                    || Character.isDigit(vChar)
                    || (vChar == KeyEvent.VK_PERIOD))) {
                evt.consume();
            }
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed

        if (this.tblPaquete.getSelectedRow() == -1) {//no se selecciono niguna fila

            JOptionPane.showMessageDialog(null, "Debe seleccionar un paquete para la simulacion", "Error", JOptionPane.ERROR_MESSAGE);

        } else {// se selecciono alguna fila

            int dialogButton = JOptionPane.YES_NO_OPTION;
            int dialogResult = JOptionPane.showConfirmDialog(null, "¿Empezar Simulación de Tracking?", "Confirmación", dialogButton);
            if (dialogResult == JOptionPane.YES_OPTION) {
                //elimino envio

                // codigo para obtener el ObjetoTablaEnvio de la fila seleccionada
                //            int numFila = this.tblPaquete.getSelectedRow();
                //            System.out.println(this.listaFilasTablaPaquetes.get(numFila).getIdPaquete());
                //            SimuTracking ventanaTracking = new SimuTracking(this.listaFilasTablaPaquetes.get(numFila));
                //            ventanaTracking.setVisible(true);
                //            this.dispose();
                int numFila = this.tblPaquete.getSelectedRow();

                EstadoRegistro ventanaEspera = new EstadoRegistro();
                ventanaEspera.setTitle("Simulación de Tracking de Paquetes");
                ventanaEspera.getjLabel1().setText("Cargando datos para la simulación. Por favor espere.");
                new WorkerTracking(this, numFila, ventanaEspera).execute();
                //this.setFocusableWindowState(false);
                this.dispose();
                ventanaEspera.setVisible(true);

            }
            if (dialogResult == JOptionPane.NO_OPTION) {
                //this.dispose();
            }
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreActionPerformed

    private void limpiarTxt() {
        this.txtIDPaq.setText("");
        this.txtNombre.setText("");
        this.txtDocId.setText("");
        this.txtApPat.setText("");
        if (listaFilasTablaPaquetes != null) {
            for (int i = numfilas - 1; i >= 0; i--) {
                modeloTablaPaquetes.removeRow(i);
            }
            listaFilasTablaPaquetes.clear();
        }
        numfilas = 0;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BusquedaPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BusquedaPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BusquedaPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BusquedaPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BusquedaPaquete().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel apellido;
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JLabel dni;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel nombre;
    private javax.swing.JRadioButton rdEmpresa;
    private javax.swing.JRadioButton rdPersona;
    private javax.swing.JTable tblPaquete;
    private javax.swing.JTextField txtApPat;
    private javax.swing.JTextField txtDocId;
    private javax.swing.JTextField txtIDPaq;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

    private void iniciaCampos(int i) {

        if (i == 1) {
            MaxLengthTextDocument maxID = new MaxLengthTextDocument();
            MaxLengthTextDocument maxApPat = new MaxLengthTextDocument();
            MaxLengthTextDocument maxNom = new MaxLengthTextDocument();
            MaxLengthTextDocument maxDoc = new MaxLengthTextDocument();

            maxNom.setMaxChars(15);
            maxApPat.setMaxChars(20);
            maxID.setMaxChars(5);
            maxDoc.setMaxChars(8);

            txtIDPaq.setDocument(maxID);
            txtNombre.setDocument(maxNom);
            txtApPat.setDocument(maxApPat);
            txtDocId.setDocument(maxDoc);
        } else {
            MaxLengthTextDocument maxID = new MaxLengthTextDocument();
            MaxLengthTextDocument maxApPat = new MaxLengthTextDocument();
            MaxLengthTextDocument maxNom = new MaxLengthTextDocument();
            MaxLengthTextDocument maxDoc = new MaxLengthTextDocument();

            maxNom.setMaxChars(30);
            maxApPat.setMaxChars(20);
            maxID.setMaxChars(5);
            maxDoc.setMaxChars(11);

            txtIDPaq.setDocument(maxID);
            txtNombre.setDocument(maxNom);
            txtApPat.setDocument(maxApPat);
            txtDocId.setDocument(maxDoc);
        }
    }
}
